#include "pch.h"
#include "StringUtils.h"

std::string StringUtils::Utf16ToUtf8(System::String^ utf16)
{
	// get unsigned char array from System::String
	array<wchar_t>^ chArray = utf16->ToCharArray();
	array<unsigned char, 1>^ arr = System::Text::Encoding::UTF8->GetBytes(chArray);

	// declare a C array
	char* c_arr = new char[arr->Length + 1];
	memset(c_arr, NULL, arr->Length + 1);

	System::IntPtr c_arr_ptr(c_arr);

	// copy from .NETs unsigned char array to char array
	System::Runtime::InteropServices::Marshal::Copy(arr, 0, c_arr_ptr, arr->Length);

	std::string str = c_arr;
	delete[] c_arr;
	c_arr = NULL;
	return str;
}

System::String^ StringUtils::Utf8ToUtf16(const std::string& cpp_string)
{
	array<unsigned char>^ c_array = gcnew array<unsigned char>(cpp_string.length());
	for (size_t i = 0; i < cpp_string.length(); i++)
	{
		c_array[i] = cpp_string[i];
	}

	System::Text::Encoding^ u8enc = System::Text::Encoding::UTF8;
	System::String^ u8_array = u8enc->GetString(c_array);
	return u8_array;
}
